package com.lz.ionicbase.engine;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.lz.ionicbase.engine.callback.AppCallback;
import com.lz.ionicbase.model.LoginBean;
import com.lz.ionicbase.ui.activity.action.IloginView;
import com.lzy.okgo.OkGo;

import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by wyfei on 2017/2/9.
 */
public class LoginHelper extends BaseHelper{

    private static final String TAG = "SetHelper";
    private Context context;


    private IloginView loginView;
    private String name;
    private String psd;

    public LoginHelper(IloginView iAction) {
        super(iAction, (Context) iAction);
        loginView = iAction;
        context = (Context) iAction;
    }

    public void login() {
        Map<String, String> loginParam = loginView.getLoginParam();
        name = loginParam.get("loginName");
        psd = loginParam.get("password");

        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(psd)) {
            String url = loginView.getUrl();

            getData(url, loginParam, new AppCallback<LoginBean>(context) {
                @Override
                public void onSuccess(LoginBean resObj, Call call, Response response) {
                    if(resObj.code ==100){
                        String username = resObj.getUsername();
                        Log.i("------", "username------"+username);
                        loginView.toMainActivity(resObj.getToken(), resObj.code+"" ,username);
                    }else {
                        String desc = resObj.getDesc();
                        loginView.ShowOtherError(desc);
                    }
                }
                @Override
                public LoginBean convertSuccess(Response response) throws Exception {
                    LoginBean resObj = new Gson().fromJson(response.body().string(), LoginBean.class);
                    return resObj;
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    loginView.ShowError();
                }
            });
        } else {
            loginView.ShowEmpty();
        }
    }

    protected void onError(){

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);

        loginView = null;
        context = null;
    }
}
